package com.azxc.rapid.plus.user.controller;


import com.azxc.rapid.core.boot.ctrl.RapidController;
import com.azxc.rapid.core.log.exception.ServiceException;
import com.azxc.rapid.core.mp.support.Condition;
import com.azxc.rapid.core.redis.cache.RapidRedis;
import com.azxc.rapid.core.secure.utils.AuthUtil;
import com.azxc.rapid.core.tool.api.R;
import com.azxc.rapid.core.tool.node.ForestNodeMerger;
import com.azxc.rapid.core.tool.utils.BeanUtil;
import com.azxc.rapid.core.tool.utils.Func;
import com.azxc.rapid.core.tool.utils.StringUtil;
import com.azxc.rapid.plus.system.service.IDeptPlusService;
import com.azxc.rapid.plus.user.service.IUserPlusService;
import com.azxc.rapid.plus.user.service.IWestoneStaffService;
import com.azxc.rapid.plus.user.service.IWestoneVersionService;
import com.azxc.rapid.plus.user.vo.DeptUserVO;
import com.azxc.rapid.plus.user.vo.UserTreeVO;
import com.azxc.rapid.plus.user.vo.WestoneBaseMsg;
import com.azxc.rapid.system.entity.Dept;
import com.azxc.rapid.system.feign.ISysClient;
import com.azxc.rapid.system.user.entity.User;

import com.azxc.rapid.system.user.vo.UserVO;
import com.azxc.rapid.system.vo.DeptVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 控制器
 */
@RestController
@Slf4j
@Api(value = "用户信息")
@RequestMapping("/userPlus")
public class UserPlusController extends RapidController {

	@Autowired
	private  IUserPlusService userService;

	@Autowired
	private  ISysClient iSysClient;

	@Autowired
	private RapidRedis rapidRedis;

	@Autowired
	private  IDeptPlusService deptService;

	@Value("${supervise.roleIds:}")
	private String roleids;

	@Autowired
	private IWestoneVersionService westoneVersionService;

	@Autowired
	private IWestoneStaffService westoneStaffService;

	/**
	 * 获取当前登录的用户的信息-包括所属行政区域code，所属行政区域名称，所属行政区域级别
	 */
	@ApiOperationSupport(order = 18)
	@ApiOperation(value = "当前登录的用户的信息", notes = "当前登录的用户的信息")
	@GetMapping("/getUserVoInfo")
	public R<UserVO> getUserVoInfo() {
		UserVO userVo = userService.getUserVoInfo();
		return R.data(userVo);
	}


	/**
	 * 根据部门id,获取部门下的人员
	 */
	@GetMapping("/getUserListByDeptId")
	@ApiOperationSupport(order = 19)
	@ApiOperation(value = "根据部门id获取部门下的人员", notes = "根据部门id获取部门下的人员")
	public R<List<User>> getUserListByDeptId(String deptId) {
		User user = new User();
		user.setDeptId(deptId);
		user.setIsDeleted(0);
		QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user);
		List<User> list = userService.list((!AuthUtil.isAdministrator()) ? queryWrapper.lambda() : queryWrapper);
		for (User userData : list) {
			userData.setPassword("******");
			userData.setPostName(iSysClient.getPostName(Long.valueOf(userData.getPostId())).getData());
		}
		return R.data(list);
	}

	/**
	 * 人员选择器
	 */
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "人员选择器", notes = "传入部门父id")
	@GetMapping("/userTree")
	public R<List<UserTreeVO>> userTree(String parentDeptId, String search) {
		List<UserTreeVO> tree = new ArrayList<>();
		if (("00".equals(parentDeptId) || Func.isEmpty(parentDeptId)) && Func.isEmpty(search)) {
			tree = userService.allTree();
		} else if (Func.isNotEmpty(parentDeptId) && Func.isEmpty(search)) {
			String[] split = parentDeptId.split(",");
			for (int i = 0; i < split.length; i++) {
				String deptId = split[i];
				tree.addAll(userService.tree(Func.toLong(deptId)));
			}
		}
		return R.data(tree);
	}


	/**
	 * 综合监管人员选择器，会根据nacos中配置的角色id和登录人所在部门的行政区域编码进行关联
	 */
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "综合监管同部门人员选择器", notes = "传入部门父id")
	@GetMapping("/userTreeForSupervise")
	public R<List<UserTreeVO>> userTreeForSupervise() {
		List<UserTreeVO> tree = new ArrayList<>();
		List<UserTreeVO> rlist = new ArrayList<>();
		log.info("nacos 角色id："+roleids);
		/*if(StringUtil.isEmpty(roleids)){
			roleids="1563718313344978946,1563718413282660354,1563718545843638274";
		}*/
		/*Dept dept = iSysClient.getDept(Long.parseLong(AuthUtil.getDeptId())).getData();
		if(null==dept||null==dept.getId()){
			throw new ServiceException("获取登录人所在部门失败!");
		}
		String region = dept.getRegionCode();
		List<Dept> deptList =iSysClient.getDeptChild(dept.getParentId()).getData();

		if(CollectionUtils.isEmpty(deptList)){
			throw new ServiceException("获取登录人所在部门父级和同级的部门列表失败！");
		}*/
		/*deptList.forEach(a->{
			//如果区域编码包含登录人所在的区域编码，则加入
			if(a.getRegionCode().contains(region)){
 				tree.addAll(userService.tree(a.getId()));
			}
		});*/
		tree.addAll(userService.tree(Long.parseLong(AuthUtil.getDeptId())));
		//过滤角色

		if(StringUtil.isNotBlank(roleids)){
			List<String> rr= Arrays	.stream(roleids.split(",")).collect(Collectors.toList());
			tree.stream().forEach(b->{
				log.info(b.toString());
				if(!CollectionUtils.isEmpty(b.getChildren())){
					b.setHasChildren(true);
					List tmpChildTree=	b.getChildren();
					UserTreeVO newVo = new UserTreeVO();
					BeanUtil.copy(b,newVo);
					newVo.setChildren(null);
					List<UserTreeVO> newChildTree=	new ArrayList<>();
					for(int k=0;k<tmpChildTree.size();k++){
						Map tmap =	(Map) tmpChildTree.get(k);
						if(null!=tmap.get("roleId")&&tmap.get("roleId").toString().length()>0){
							String[] roleList= tmap.get("roleId").toString().split(",");
							for(String tmpRole:roleList){
								if(rr.contains(tmpRole)){
									newChildTree.add(b.getChildren().get(k));
									break;
								}
							}
						}
					}

					b.setChildren(newChildTree);
				}else {
					b.setHasChildren(false);
				}
			});
		}

		rlist =	ForestNodeMerger.merge(tree);
		return R.data(rlist);
	}


	/**
	 * 综合监管人员选择器，会根据nacos中配置的角色id和登录人所在部门的行政区域编码进行关联
	 */
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "综合监管人员选择器，筛选当前登录人所在部门的下级部门人员", notes = "传入部门父id")
	@GetMapping("/userChildTreeForSupervise")
	public R<List<UserTreeVO>> userChildTreeForSupervise() {
		List<UserTreeVO> tree = new ArrayList<>();
		List<UserTreeVO> rlist = new ArrayList<>();
		log.info("nacos 角色id："+roleids);
		/*if(StringUtil.isEmpty(roleids)){
			roleids="1563718313344978946,1563718413282660354,1563718545843638274";
		}*/
		Dept dept = iSysClient.getDept(Long.parseLong(AuthUtil.getDeptId())).getData();
		if(null==dept||null==dept.getId()){
			throw new ServiceException("获取登录人所在部门失败!");
		}
		String region = dept.getRegionCode();
		//本级和本级部门
		List<Dept> deptList = null ;
		try{
			deptList =	iSysClient.getDeptChild(dept.getId()).getData();
		}catch (Exception ex){
			log.error("调用出错:"+ex.toString());
		}


		if(CollectionUtils.isEmpty(deptList)){
			throw new ServiceException("获取登录人所在部门父级和同级的部门列表失败！");
		}
		deptList.forEach(a->{
			//如果区域编码包含登录人所在的区域编码，则加入
			if(a.getRegionCode().contains(region)){
				if(a.getParentId().equals(dept.getId())||a.getId().equals(dept.getId())){
					tree.addAll(userService.tree(a.getId()));
				}
			}
		});
		//过滤角色

		if(StringUtil.isNotBlank(roleids)){
			List<String> rr= Arrays	.stream(roleids.split(",")).collect(Collectors.toList());
			tree.stream().forEach(b->{
				log.info(b.toString());
				if(!CollectionUtils.isEmpty(b.getChildren())){
					b.setHasChildren(true);
					List tmpChildTree=	b.getChildren();
					UserTreeVO newVo = new UserTreeVO();
					BeanUtil.copy(b,newVo);
					newVo.setChildren(null);
					List<UserTreeVO> newChildTree=	new ArrayList<>();
					for(int k=0;k<tmpChildTree.size();k++){
						Map tmap =	(Map) tmpChildTree.get(k);
						if(null!=tmap.get("roleId")&&tmap.get("roleId").toString().length()>0){
							String[] roleList= tmap.get("roleId").toString().split(",");
							for(String tmpRole:roleList){
								if(rr.contains(tmpRole)){
									newChildTree.add(b.getChildren().get(k));
									break;
								}
							}
						}
					}

					b.setChildren(newChildTree);
				}else {
					b.setHasChildren(false);
				}
			});
		}

		rlist =	ForestNodeMerger.merge(tree);
		return R.data(rlist);
	}

	/**
	 * 综合监管人员选择器，会根据nacos中配置的角色id和登录人所在部门的行政区域编码进行关联
	 */
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "综合监管人员选择器，筛选当前登录人所在部门的子一级部门人员", notes = "传入部门父id")
	@GetMapping("/userChildForSupervise")
	public R<List<UserTreeVO>> userChildForSupervise(String userName) {
		List<UserTreeVO> tree = new ArrayList<>();
		List<UserTreeVO> newtree = new ArrayList<>();
		List<UserTreeVO> lasttree = new ArrayList<>();
		List<UserTreeVO> rlist = new ArrayList<>();
		log.info("nacos 角色id："+roleids);
		/*if(StringUtil.isEmpty(roleids)){
			roleids="1563718313344978946,1563718413282660354,1563718545843638274";
		}*/
		Dept dept = iSysClient.getDept(Long.parseLong(AuthUtil.getDeptId())).getData();
		if(null==dept||null==dept.getId()){
			throw new ServiceException("获取登录人所在部门失败!");
		}
		String region = dept.getRegionCode();
		//本级和本级部门
		List<DeptVO> deptList = null ;
		try{
			deptList =	deptService.ChildDeptByDeptId(dept.getId().toString());
		}catch (Exception ex){
			log.error("调用出错:"+ex.toString());
		}


		if(CollectionUtils.isEmpty(deptList)){
			throw new ServiceException("获取登录人所在部门父级和同级的部门列表失败！");
		}
		deptList.forEach(a->{
			//如果区域编码包含登录人所在的区域编码，则加入
			if(a.getRegionCode().contains(region)){
				if(a.getParentId().equals(dept.getId())||a.getId().equals(dept.getId())){
					tree.addAll(userService.tree(a.getId()));
				}
			}
		});
		//过滤角色

		if(StringUtil.isNotBlank(roleids)){
			List<String> rr= Arrays	.stream(roleids.split(",")).collect(Collectors.toList());
			tree.stream().forEach(b->{
				log.info(b.toString());
				if(!CollectionUtils.isEmpty(b.getChildren())){
					b.setHasChildren(true);
					List tmpChildTree=	b.getChildren();
					UserTreeVO newVo = new UserTreeVO();
					BeanUtil.copy(b,newVo);
					newVo.setChildren(null);
					List<UserTreeVO> newChildTree=	new ArrayList<>();
					for(int k=0;k<tmpChildTree.size();k++){
						Map tmap =	(Map) tmpChildTree.get(k);
						if(null!=tmap.get("roleId")&&tmap.get("roleId").toString().length()>0){
							String[] roleList= tmap.get("roleId").toString().split(",");
							for(String tmpRole:roleList){
								if(rr.contains(tmpRole)){
									newChildTree.add(b.getChildren().get(k));
									break;
								}
							}
						}
					}

					b.setChildren(newChildTree);
				}else {
					b.setHasChildren(false);
				}
			});
		}
		//过滤用户名，如果没有用户 也去掉部门
		if(StringUtil.isNotBlank(userName)){
			tree.stream().forEach(b->{
				if(!CollectionUtils.isEmpty(b.getChildren())){
					b.setHasChildren(true);
					List tmpChildTree=	b.getChildren();
					UserTreeVO newVo = new UserTreeVO();
					BeanUtil.copy(b,newVo);
					newVo.setChildren(null);
					List<UserTreeVO> newChildTree=	new ArrayList<>();
					for(int k=0;k<tmpChildTree.size();k++){
						Map tmap =	(Map) tmpChildTree.get(k);
						if(null!=tmap.get("name")&&tmap.get("name").toString().length()>0&&tmap.get("name").toString().contains(userName)){
							newChildTree.add(b.getChildren().get(k));
						}
					}
					if(newChildTree.size()>0){
						b.setChildren(newChildTree);
						newtree.add(b);
					}
				}else {
					b.setHasChildren(false);
				}
			});
			lasttree = newtree;
		}else{
			lasttree = tree;
		}
		rlist =	ForestNodeMerger.merge(lasttree);
		return R.data(rlist);
	}

	/**
	 * 综合监管人员选择器，会根据nacos中配置的角色id和登录人所在部门的行政区域编码进行关联
	 */
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "综合监管人员选择器，筛选当前登录人所在部门的部门人员", notes = "传入部门父id")
	@GetMapping("/userForSupervise")
	public R<List<UserTreeVO>> userForSupervise(String userName) {
		List<UserTreeVO> tree = new ArrayList<>();
		List<UserTreeVO> newtree = new ArrayList<>();
		List<UserTreeVO> lasttree = new ArrayList<>();
		List<UserTreeVO> rlist = new ArrayList<>();
		log.info("nacos 角色id："+roleids);
		/*if(StringUtil.isEmpty(roleids)){
			roleids="1563718313344978946,1563718413282660354,1563718545843638274";
		}*/
		Dept dept = iSysClient.getDept(Long.parseLong(AuthUtil.getDeptId())).getData();
		if(null==dept||null==dept.getId()){
			throw new ServiceException("获取登录人所在部门失败!");
		}
		String region = dept.getRegionCode();
		//本级和本级部门
		List<DeptVO> deptList = null ;
		try{
			deptList =	deptService.deptByDeptId(dept.getId().toString());
		}catch (Exception ex){
			log.error("调用出错:"+ex.toString());
		}


		if(CollectionUtils.isEmpty(deptList)){
			throw new ServiceException("获取登录人所在部门父级和同级的部门列表失败！");
		}
		deptList.forEach(a->{
			//如果区域编码包含登录人所在的区域编码，则加入
			if(a.getRegionCode().contains(region)){
				if(a.getParentId().equals(dept.getId())||a.getId().equals(dept.getId())){
					tree.addAll(userService.tree(a.getId()));
				}
			}
		});
		//过滤角色

		if(StringUtil.isNotBlank(roleids)){
			List<String> rr= Arrays	.stream(roleids.split(",")).collect(Collectors.toList());
			tree.stream().forEach(b->{
				log.info(b.toString());
				if(!CollectionUtils.isEmpty(b.getChildren())){
					b.setHasChildren(true);
					List tmpChildTree=	b.getChildren();
					UserTreeVO newVo = new UserTreeVO();
					BeanUtil.copy(b,newVo);
					newVo.setChildren(null);
					List<UserTreeVO> newChildTree=	new ArrayList<>();
					for(int k=0;k<tmpChildTree.size();k++){
						Map tmap =	(Map) tmpChildTree.get(k);
						if(null!=tmap.get("roleId")&&tmap.get("roleId").toString().length()>0){
							String[] roleList= tmap.get("roleId").toString().split(",");
							for(String tmpRole:roleList){
								if(rr.contains(tmpRole)){
									newChildTree.add(b.getChildren().get(k));
									break;
								}
							}
						}
					}

					b.setChildren(newChildTree);
				}else {
					b.setHasChildren(false);
				}
			});
		}
		//过滤用户名，如果没有用户 也去掉部门
		if(StringUtil.isNotBlank(userName)){
			tree.stream().forEach(b->{
				if(!CollectionUtils.isEmpty(b.getChildren())){
					b.setHasChildren(true);
					List tmpChildTree=	b.getChildren();
					UserTreeVO newVo = new UserTreeVO();
					BeanUtil.copy(b,newVo);
					newVo.setChildren(null);
					List<UserTreeVO> newChildTree=	new ArrayList<>();
					for(int k=0;k<tmpChildTree.size();k++){
						Map tmap =	(Map) tmpChildTree.get(k);
						if(null!=tmap.get("name")&&tmap.get("name").toString().length()>0&&tmap.get("name").toString().contains(userName)){
							newChildTree.add(b.getChildren().get(k));
						}
					}
					if(newChildTree.size()>0){
						b.setChildren(newChildTree);
						newtree.add(b);
					}
				}else {
					b.setHasChildren(false);
				}
			});
			lasttree = newtree;
		}else{
			lasttree = tree;
		}
		rlist =	ForestNodeMerger.merge(lasttree);
		return R.data(rlist);
	}

	/**
	 * 部门选择器
	 */
	@ApiOperationSupport(order = 21)
	@ApiOperation(value = "部门选择器", notes = "传入部门父id")
	@GetMapping("/loadTree")
	public R<List<UserTreeVO>> loadTree(String parentDeptId, String search) {
		List<UserTreeVO> tree = new ArrayList<>();
		if (("00".equals(parentDeptId) || Func.isEmpty(parentDeptId)) && Func.isEmpty(search)) {
			tree = userService.loadAllTree();
		} else if (Func.isNotEmpty(parentDeptId) && Func.isEmpty(search)) {
			String[] split = parentDeptId.split(",");
			for (int i = 0; i < split.length; i++) {
				String deptId = split[i];
				tree.addAll(userService.loadTree(Func.toLong(deptId)));
			}
		}
		return R.data(tree);
	}

	/**
	 * 根据部门查询人员
	 *
	 * @param deptUserVO
	 * @return
	 */
	@PostMapping("/selectUserByDept")
	@ApiOperationSupport(order = 22)
	@ApiOperation(value = "根据部门查询人员", notes = "传入部门id")
	public R<List<User>> selectUserByDept(@RequestBody DeptUserVO deptUserVO) {
		List<User> userList = userService.selectUserByDept(deptUserVO);
		return R.data(userList);
	}


	@ApiOperationSupport(order = 23)
	@ApiOperation(value = "解锁用户", notes = "传入用户名")
	@GetMapping("/unlock/{key}")
	public R delete(@PathVariable String key) {
		rapidRedis.del("loginLock:" + key);
		return R.data("解锁成功");
	}

	@ApiOperationSupport(order = 18)
	@ApiOperation(value = "全量同步卫士通通讯录", notes = "全量同步卫士通通讯录")
	@GetMapping("/synchronizationWestonAll")
	public R synchronizationWestonAll() {
		return R.status(westoneVersionService.synchronizationAll());
	}

	@ApiOperationSupport(order = 18)
	@ApiOperation(value = "增量同步卫士通通讯录", notes = "增量同步卫士通通讯录")
	@GetMapping("/addChangeWeston")
	public R addChangeWeston() {
		return R.status(westoneVersionService.addChange());
	}

	@ApiOperationSupport(order = 18)
	@ApiOperation(value = "给卫士通推送消息", notes = "给卫士通推送消息")
	@PostMapping("/sendMsgToWestoneByMobile")
	public R sendMsgToWestoneByMobile(@RequestBody WestoneBaseMsg westoneBaseMsg) {
		return R.status(westoneStaffService.pushMessageByMobile(westoneBaseMsg.getRecipients(),westoneBaseMsg.getBadge_number(),
			westoneBaseMsg.getMsgType(), westoneBaseMsg.getSubject(), westoneBaseMsg.getContent(), westoneBaseMsg.getActions()));
	}



}
